<?php
namespace app\user\model;

use think\Session;
use \app\common\traits\model\UserOperateCheck;
use app\common\model\Users as commonUsers;

class Users extends commonUsers
{
    use UserOperateCheck;
    //赠送的旅行币
    const PRESENT_INTEGRAL = 10000;

    public function addUser($user_info = [])
    {
    	if (true == !$this->checkUser($user_info, ['mobile'])) {
    		$user_info['password'] = md5($user_info['password']);
            $user_info['sign'] = $this->uuid();
    		return self::create($user_info);
    	}else {
    		return false;
    	}	
    }
    /**
     * 校验用户信息是否存在
     * @param  [type] $user_info [description]
     * @param  array  $onlys     [description]
     * @return [type]            [description]
     */
    public function checkUser($user_info, $onlys = [])
    {
    	$user_info = $onlys ? array_intersect_key($user_info, array_flip($onlys)) : $user_info;
    	if (!empty($user_info)) {
    		foreach ($user_info as $key => $data) {
	    		if (self::getUserInfo([$key => $data])) {
	    			$this->error = lang($key);
	            	return true;
	        	}
	    	}
    	}   	
    	return false;
    }
    /**
     * [getUserInfo 重写的]
     * @param  array  $where [description]
     * @param  string $field [description]
     * @return [type]        [description]
     */
    public static function getUserInfo($where = [], $field = '')
    {
        if (empty($where)) {
            return false;
        }
        if ($userInfo = self::get($where)) {
            if ($field) {
                if (isset($userInfo->$field)) {
                    return $userInfo->$field; 
                }
                return false;
            }
            return $userInfo;
        }
        return false;        
        
    }
    /**
     * 获取登录用户信息
     * @param  string $field [description]
     * @return [type]        [description]
     */
    public static function getLoginUserInfo($field = '')
    {
        if (empty(self::$loginuser)) {
            self::$loginuser = self::getUserInfo(['id' => session('user.id')]);
        }
        if ($field) {
            if (isset(self::$loginuser[$field])) {
                return self::$loginuser[$field]; 
            }
            return false;
        }
        return self::$loginuser;
    }
    /* 登录
    * @param  [type] $account     [description]
    * @param  [type] $password    [description]
    * @param  [type] $remember_me [description]
    * @return [type]              [description]
     */
    public  function login($account, $password, $remember_me = null)
    {
       $this->clearUserSession();
        if ($this->checkOperateCount('userlogin')) {
          if ($userInfo = self::getUserInfo(['mobile' => $account])) {
               if (md5($password) === $userInfo['password']) {
                  $this->initOperateCount('userlogin');
                  $this->setUserSession($userInfo, $remember_me);
                  self::$user_info = $userInfo;
                  return true;
               }else{
                    //密码错误
                   $this->error = lang('password is error');
               }
           }else{
               //用户不存在
               $this->error = lang('this user is not empty');
           }
            $this->addOperateCount('userlogin');
        }else{
           //超限
           $this->error = lang('this user login fail too many');
       }
       return false;
    }

    /**
     * 设置用户session信息
     * @param [type] $data        [description]
     * @param [type] $remember_me [description]
     */
    private function setUserSession($data, $remember_me)
    {
        if ($remember_me == true) {
            cookie('token', $data->id, 31536000);
        }
        $data->login_session_id = session_id();
        $data->save();
        $token = $this->getToken($data->id);
        Session::set('token', $token);
        Session::set('user.login_session_id', session_id());
        Session::set('user.id', $data->id);
        Session::set('user.mobile', $data->mobile);
    }
    /**
     * 判断是否已经登陆
     * @return [type] [description]
     */
    public function checkLogin()
    {
        if ($user_token = cookie('token')) {
             if ($login_user = self::getUserInfo(['id' => $user_token])) {
                if (false == Session::has('user')) {
                	$this->setUserSession($login_user, true);
                }
            }
        }

        if (Session::has('user')) {
            $login_session_id = self::getLoginUserInfo('login_session_id');
            if ($login_session_id !== Session::get('user.login_session_id')){
                self::$loginuser = '';
                $this->logout();
                return false;
            }
        }
        return Session::has('user') ? true : false;    
    }
    /**
     * 清除用户session信息
     * @return [type] [description]
     */
    public  function clearUserSession()
    {
        Session::delete('user');
    }
    /**
     * 退出登录
     * @return [type] [description]
     */
    public function logout()
    {
        $this->clearUserSession();
        cookie('token', null);
        return true;
    }
    /**
     * [BindRv 绑定房车]
     * @param string $value [description]
     */
    public function BindRv($data,$caravan_user_id)
    {
        $this->startTrans();
        $user_id = session('user.id');
        try{
            $re = model('common/Caravans')->getCaravanInfo($caravan_user_id)->initCaravanCarlendar(['start_date' => $data['sdate'], 'end_date' => $data['edate']]);
            //返还旅行币
            $amount = self::PRESENT_INTEGRAL;
            $res    = model('common/Capitals')->incIntegral($amount, $user_id, $option = []);
            //status=1标示有车会员
            $resu   = model('Users')->where('id',$user_id)->setField('status',1);
            //绑定成功
            $this->commit();
            return true;
            }catch(\Exception $e){
            $this->rollback();    
            $this->error = $e->getMessage();
        }
        return false;
    }
    //////////////////////会员个人资料管理/////////////////////////
    /**
     * [updatePersonInfo 更新会员资料]
     * @param  [type] $id                [description]
     * @param  [type] $person_info_array [description]
     * @return [type]                    [description]
     */
    public function updatePersonInfo($id, $person_info_array)
    {
        return $this->where('id',$id)->update($person_info_array);
    }
    /**
     * [getCheckNickName 检测空字段]
     * @return [type] []
     */
    public function getCheckNull($info_array)
    {
        foreach ($info_array as $key => $value) {
            if (empty($value)) {
                return false;
            }
        }
        return true;
    }



}
